import { nodeResolve } from "@rollup/plugin-node-resolve";
import babel from "@rollup/plugin-babel";
import commonjs from "@rollup/plugin-commonjs";
// import analyzer from "rollup-plugin-analyzer";
import typescript from "rollup-plugin-typescript2";

import replace from "@rollup/plugin-replace";
import { readFileSync } from "fs";

const pkg = JSON.parse(readFileSync("package.json", { encoding: "utf8" }));

const isProduction = process.env.NODE_ENV === "production";
const useAnalyzer = process.env.ANALYZER === "analyzer";
const replaceOpts = {
  "process.env.BABEL_ENV": null,
  __DEV__: !isProduction,
  "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
};

const babelOpts = {
  exclude: "node_modules/**",
  extensions: [".ts", ".js"],
  presets: ["@babel/preset-env", "@babel/preset-typescript"],
};

const terserOpts = {
  compress: {
    passes: 2,
  },
  output: {
    comments(node, comment) {
      return comment.value.trim().startsWith("syzlm@");
    },
  },
};

export default (async () => [
  {
    input: "./src/index.ts",
    output: [
      {
        file: `./lib/umd/evaluator.min.js`,
        format: "umd",
        name: "Evaluator",
        sourcemap: true,
        banner: generateBanner("UMD"),
      },
      {
        file: `./lib/system/evaluator.min.js`,
        format: "system",
        sourcemap: true,
        banner: generateBanner("SystemJS"),
      },
      {
        file: `./lib/esm/evaluator.min.js`,
        format: "esm",
        sourcemap: true,
        banner: generateBanner("ESM"),
      },
    ],
    plugins: [
      typescript({
        tsconfig: "./tsconfig.json", // 指定你的 tsconfig
        useTsconfigDeclarationDir: true, // 遵循 tsconfig 中的 declarationDir
      }),
      replace(replaceOpts),
      nodeResolve({ extensions: [".ts", ".js"] }),
      babel(babelOpts),
      commonjs(),
      isProduction &&
        (await import("@rollup/plugin-terser")).default(terserOpts),
      //   useAnalyzer && analyzer(),
    ],
  },
  {
    input: "./src/index.ts",
    output: {
      file: `./lib/es2015/evaluator.min.js`,
      format: "esm",
      sourcemap: true,
      banner: generateBanner("ES2015"),
    },
    plugins: [
      typescript({
        tsconfig: "./tsconfig.json", // 指定你的 tsconfig
        useTsconfigDeclarationDir: true, // 遵循 tsconfig 中的 declarationDir
      }),
      replace(replaceOpts),
      nodeResolve({ extensions: [".ts", ".js"] }),
      babel(
        Object.assign({}, babelOpts, {
          envName: "esm",
        })
      ),
      commonjs(),
      isProduction &&
        (await import("@rollup/plugin-terser")).default(
          Object.assign({}, terserOpts, {
            ecma: 6,
            module: true,
          })
        ),
      //   useAnalyzer && analyzer(),
    ],
  },
])();

function generateBanner(format) {
  return `/* javascript模版计算：evaluator@${pkg.version} - ${format} - ${
    isProduction ? "prod" : "dev"
  } */`;
}
